package com.oauth2.demo.utils;

import cn.hutool.core.util.StrUtil;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.stats.CacheStats;

import java.sql.Struct;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;

public class LocalCacheUtil {


    private final static Long SIZE = 100L;
    private final static Long TIME = 5L;
    private final static Cache<String, Object> cache;

    static {
        cache = Caffeine.newBuilder()
                .maximumSize(SIZE)
                .expireAfterWrite(TIME, TimeUnit.MINUTES)
                .build();
    }


    public static void put(String key, final Object value) {
        cache.put(key, value);
    }

    public static Object get(String key) {
        if (StrUtil.isNotBlank(key)){
            return  cache.getIfPresent(key);
        }
        return null;
    }


    public static boolean containsKey(String key) {
        return asMap().containsKey(key);
    }


    public static boolean containsValue(String value) {
        return asMap().containsValue(value);
    }


    public static void remove(Object key) {
        cache.invalidate(key);
    }


    public static CacheStats cacheStats() {
        return  cache.stats();
    }


    public static void clear() {
        cache.invalidateAll();
    }


    public static  ConcurrentMap<String, Object> asMap() {
        return  cache.asMap();
    }


    public static Collection<Object> values() {
        return asMap().values();
    }


    public static long size() {
        return  cache.estimatedSize();
    }


    public static void cleanUp() {
        cache.cleanUp();
    }


    public Object getOrDefault(String k, Object defaultValue) {
        String v;
        return ((v = (String) get(k)) != null) ? v : defaultValue;
    }


    public Set<Map.Entry<String, Object>> entrySet() {
        return asMap().entrySet();
    }


    public static void main(String[] args) {
        // 创建一个缓存，最大容量100，过期时间5分钟
//        Cache<String, String> cache = Caffeine.newBuilder()
//                .maximumSize(100)
//                .expireAfterWrite(5, TimeUnit.MINUTES)
//                .build();
        LocalCacheUtil util = new LocalCacheUtil();
        // 存入数据到缓存
        cache.put("key1", "value1");

        System.out.println(util.containsKey("key1"));
        // 从缓存中获取数据
        Object value = cache.getIfPresent("key1");
        System.out.println(value); // 输出 value1

        // 通过缓存统计信息
        CacheStats stats = cache.stats();
        System.out.println("Cache hits: " + stats.hitCount());
        System.out.println("Cache misses: " + stats.missCount());
    }
}
